package com.ryze.common.dubbo.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.threadlocal.InternalThreadLocal;
import org.slf4j.MDC;

import java.util.HashMap;
import java.util.Map;

public class RyzeRpcContext {

    private static final InternalThreadLocal<RyzeRpcContext> LOCAL = new InternalThreadLocal<RyzeRpcContext>() {
        @Override
        protected RyzeRpcContext initialValue() {
            return new RyzeRpcContext();
        }
    };

    private String uid;
    private String uname;
    private String sid;
    private String projectGroup;

    public static final String K_UID = "PS-X-UID";
    public static final String K_UNAME = "PS-X-UNAME";
    public static final String K_SID = "PS-X-SID";
    public static final String K_PROJECTGROUP = "projectGroup";


    public Map<String,Object> getContextParams(){
        Map<String,Object> params = new HashMap<>();
        if(StringUtils.isNotBlank(uid)) {
            params.put(K_UID, uid);
        }
        if(StringUtils.isNotBlank(uname)) {
            params.put(K_UNAME, uname);
        }
        if(StringUtils.isNotBlank(sid)) {
            params.put(K_SID, sid);
        }
        if(StringUtils.isNotBlank(projectGroup)) {
            params.put(K_PROJECTGROUP, projectGroup);
        }
        return params;
    }

    public void extractContextParams(Map<String,Object> params){
        setUid((String)params.get(K_UID));
        setUname((String) params.get(K_UNAME));
        setSid((String) params.get(K_SID));
        setProjectGroup((String) params.get(K_PROJECTGROUP));
    }

    protected RyzeRpcContext() {
    }

    /**
     * get context.
     *
     * @return context
     */
    public static RyzeRpcContext getContext() {
        return LOCAL.get();
    }

    /**
     * remove context.
     */
    public static void removeContext() {
        LOCAL.remove();
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
        MDC.put(K_UID,uid);
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
        MDC.put(K_UNAME,uname);
    }

    public String getSid() {
        return sid;
    }

    public void setSid(String sid) {
        this.sid = sid;
        MDC.put(K_SID,sid);
    }
    public String getProjectGroup() {
        return projectGroup;
    }

    public void setProjectGroup(String projectGroup) {
        this.projectGroup = projectGroup;
        MDC.put(K_PROJECTGROUP,projectGroup);
    }

}

